package city.spring.service.impl;

import city.spring.domain.entity.ClassifyTreeEntity;
import city.spring.repository.ClassifyTreeRepository;
import city.spring.service.ClassifyTreeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Service：多级分类信息
 *
 * @author 侯坤林
 * @date 2020-04-08 14:20:10
 */
@CacheConfig(cacheNames = {ClassifyTreeServiceImpl.CACHE_NAME})
@Transactional(rollbackFor = Throwable.class)
@Service
public class ClassifyTreeServiceImpl extends ServiceImpl<ClassifyTreeRepository, ClassifyTreeEntity> implements ClassifyTreeService {

    @Override
    public void saveClassifyTree(ClassifyTreeEntity entity) {
        if (!save(entity)) {
            throw new RuntimeException("保存信息失败");
        }
    }

    @Override
    public void updateClassifyTree(ClassifyTreeEntity entity) {
        // 使用 updateById(entity); 修改数据时，将会修改 entity 对象中所有非null数据，如果某个字段为null，将会忽略该字段的修改
        boolean update = updateById(entity);
        if (!update) {
            throw new RuntimeException("修改信息失败");
        }
    }

    @Override
    public void maintainParentAndSorted(List<ClassifyTreeEntity> entities) {
        List<ClassifyTreeEntity> list = new ArrayList<>();
        for (ClassifyTreeEntity entity : entities) {
            ClassifyTreeEntity classifyTreeEntity = new ClassifyTreeEntity();
            classifyTreeEntity.setId(entity.getId());
            classifyTreeEntity.setPid(entity.getPid());
            classifyTreeEntity.setSorted(entity.getSorted());
            list.add(classifyTreeEntity);
        }
        updateBatchById(list);
    }

    @Override
    public void deleteClassifyTree(String primaryKey) {
        removeById(primaryKey);
    }

    @Override
    public void deleteClassifyTree(List<String> primaryKeys) {
        removeByIds(primaryKeys);
    }
}